package com.zhuangjie.mvc.validator.handler;


import com.zhuangjie.mvc.validator.annotate.PhoneNumber;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneNumberConstraintValidator implements ConstraintValidator<PhoneNumber,String> {
    private boolean hasAreaCode;
    @Override
    public void initialize(PhoneNumber constraintAnnotation) {
        hasAreaCode = constraintAnnotation.hasAreaCode();
    }

    @Override
    public boolean isValid(String phoneNumber, ConstraintValidatorContext constraintValidatorContext) {
        if (phoneNumber == null) return false;
        if (hasAreaCode) {
            // 验证各国手机号，泛匹配，会传入+xx yyyy
            return phoneNumber.matches("^\\+?\\d+\\s+\\d+$");
        }else {
            // 只要求最少8位的纯数字
            return phoneNumber.matches("\\d{8,}");
        }
    }
}
